package com.bei_en.teacher.admin.controller.questions;

import java.util.ArrayList;
import java.util.List;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.TransactionStatus;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bei_en.teacher.admin.model.learn.vo.LearnReportVo;
import com.bei_en.teacher.admin.model.questions.bean.Questions;
import com.bei_en.teacher.admin.model.questions.condition.QuestionsCollectionCondition;
import com.bei_en.teacher.admin.model.questions.condition.QuestionsCondition;
import com.bei_en.teacher.admin.model.questions.condition.QuestionsQueryCondition;
import com.bei_en.teacher.admin.model.questions.condition.QuestionsSubtimCondition;
import com.bei_en.teacher.admin.model.questions.vo.QuestionsCollectionVo;
import com.bei_en.teacher.admin.model.questions.vo.QuestionsTypeVo;
import com.bei_en.teacher.admin.model.questions.vo.QuestionsVo;
import com.bei_en.teacher.admin.model.users.vo.UsersVo;
import com.bei_en.teacher.admin.other.Consts;
import com.bei_en.teacher.admin.service.learn.LearnReportService;
import com.bei_en.teacher.admin.service.questions.QuestionsCollectionService;
import com.bei_en.teacher.admin.service.questions.QuestionsService;
import com.bei_en.teacher.admin.service.questions.QuestionsTypeService;
import com.bei_en.teacher.admin.controller.BaseController;
import com.bei_en.common.util.ZipUtil;
import com.bei_en.common.util.interceptor.OAuthRequired;
import com.bei_en.common.web.JsonFailResult;
import com.bei_en.common.web.JsonResult;
import com.bei_en.common.web.JsonSuccessResult;
import com.bei_en.common.web.MySessionContext;
import com.mysql.fabric.xmlrpc.base.Array;

/**
 * 
 * @author Guocg
 * @date 2016-8-15 23:28:11
 */
@Controller
@RequestMapping("/api/Questions")
public class QuestionsAPPController extends BaseController {

	@Autowired
	QuestionsService questionsService;
    @Autowired
    QuestionsCollectionService questionsCollectionService;
    @Autowired
    QuestionsTypeService questionsTypeService;
    @Autowired
    LearnReportService learnReportService;
	private static String bucketName = "jiaoshi";
	private static String img_endpoint = "oss-cn-hangzhou.aliyuncs.com";// 图片服务
	/**
	 * 题库
	 * @param model
	 * @param vo
	 * @param br
	 * @param session
	 * @return
	 */
	@RequestMapping("/questions")
	@ResponseBody
	public JsonResult questions(Model model, @Valid QuestionsCondition vo,
			BindingResult br, HttpSession session) {
		
		if (br.hasErrors())
			return new JsonFailResult(session.getId(), br.getAllErrors().get(0)
					.getDefaultMessage());
		try {
			List<QuestionsVo> list = new ArrayList<QuestionsVo>();
			vo.setPageSize(Integer.MAX_VALUE);
			list = questionsService.findQuestionsPage3(vo);
			JSONObject data = new JSONObject();
			JSONArray array = new JSONArray();
			JSONObject object = null;
			QuestionsVo questionsVo = null;
			for (int i = 0; i < list.size(); i++) {
				object = new JSONObject();
				questionsVo = list.get(i);
				object.put("Id", questionsVo.getId());
				object.put("title", questionsVo.getTitle());
				if(questionsVo.getImage()==null||questionsVo.getImage()==""){
					object.put("image","");
				}else{
					object.put("image","http://" + bucketName + "."
							+ img_endpoint + "/" +questionsVo.getImage());
				}
				object.put("url","http://" + bucketName + "."
						+ img_endpoint + "/");
				if(questionsVo.getImage2()==null||questionsVo.getImage2()==""){
					object.put("image2","");
				}else{
					object.put("image2",questionsVo.getImage2());
				
				}
				object.put("year", questionsVo.getYear());
				object.put("type", questionsVo.getType());
				object.put("questionsTypeId", questionsVo.getQuestionsTypeId());
				object.put("answer", questionsVo.getAnswer());
				object.put("answers", questionsVo.getAnswers());
				object.put("fraction", questionsVo.getFraction());
				object.put("content", questionsVo.getContent());
				object.put("makeTime", questionsVo.getMakeTime());
				object.put("yesNum", questionsVo.getYesNum());
				object.put("errorNum", questionsVo.getErrorNum());
				object.put("makeNum", questionsVo.getMakeNum());
				object.put("weight", questionsVo.getWeight());
				object.put("analysis", questionsVo.getAnalysis());
				object.put("createTime", questionsVo.getCreateTime().getTime());
				
			int	 chapterId;
			int	 sectionId;
			int	 spotId;
			int	 subdivisionPointId;
			if(questionsVo.getChapter()!=null){
				chapterId	=questionsVo.getChapter().getId();
			}else{
				chapterId=0;
			}
			if(questionsVo.getSection()!=null){
				sectionId	=questionsVo.getSection().getId();
			}else{
				sectionId=0;
			}
			if(questionsVo.getSpot()!=null){
				spotId	=questionsVo.getSpot().getId();
			}else{
				spotId=0;
			}
			if(questionsVo.getSubdivisionPoint()!=null){
				subdivisionPointId	=questionsVo.getSubdivisionPoint().getId();
			}else{
				subdivisionPointId=0;
			}
			String image="";
			if(questionsVo.getImage()==null||questionsVo.getImage()==""){
				image=	 "";
			}else{
				image=	 "http://" + bucketName + "."
							+ img_endpoint + "/" +questionsVo.getImage();
			}
		
			 object.put("chapterId", chapterId);
			 object.put("sectionId", sectionId);
			 object.put("spotId",spotId);
			 object.put("subdivisionPointId",subdivisionPointId);
//				String str = "INSERT INTO `teacher`.`questions` (`id`, `title`, `image`, `type`, `questions_type_id`,`answer`, `year `answer`, `answers`,`fraction`, `content`, `analysis`,`make_time`, `yes_num`, `error_num`, `make_num`, `weight`, `chapter_id`，`section_id`，`spot_id`，`subdivisionPointId`)"
//						+ "VALUES ("
//						+ questionsVo.getId()
//						+ "' , '"
//						+ questionsVo.getTitle()
//						+ "' , '"+
//						image
//						+ "' , '"
//						+ questionsVo.getType()
//						+ "' , '"
//						+ questionsVo.getQuestionsTypeId()
//						+ "' , '"
//						+ questionsVo.getYear()
//						+ "' , '"
//						+ questionsVo.getAnswer()
//						+ "' , '"
//							+ questionsVo.getAnswers()
//						+ "' , '"
//						+ ""
//						+ questionsVo.getFraction()
//						+ "' , '"
//						+ questionsVo.getContent()
//						+ "' , '"
//						+ questionsVo.getAnalysis()
//						+ "' , '"
//						+ questionsVo.getMakeTime()
//						+ "' , '"
//						+ questionsVo.getYesNum()
//						+ "' , '"
//						+ questionsVo.getErrorNum()
//						+ "' , '"
//						+ questionsVo.getMakeNum()
//						+ "' , '"
//						+ questionsVo.getWeight()
//						+ "' , '"
//						+ questionsVo.getCreateTime().getTime() 
//						+ "' , '"
//						+ chapterId
//							+ "' , '"
//						+ sectionId
//						+ "' , '"
//						+spotId+ 
//						"' , '"
//						+subdivisionPointId+ 
//						")";
				object.put("database", "");
				array.add(object);
			}

			data.put("list", array);
			data.put(
					"table",
					"CREATE TABLE `questions` ("
							+ " `id` int(11) ,"
							+ " `title` varchar(255) DEFAULT '' COMMENT '  标题',"
							+ " `image` varchar(255) DEFAULT '' COMMENT '  图片,"
							+ " `type` int(11) DEFAULT '0' COMMENT '1是单选题2是判断题3是多选题4是名称解析5简答题',"
							+ " `questions_type_id` int(11) DEFAULT '0' COMMENT '题类型id',"
							+ " `year` varchar(255) DEFAULT '' COMMENT '答案',"
							+ " `answer` varchar(255) DEFAULT '' COMMENT '答案',"
							+ " `answers` varchar(255) DEFAULT '' COMMENT '简单题答案',"
							+ " `fraction` double DEFAULT '0' COMMENT '分数',"
							+ "`content` text COMMENT '题内容',"
							+ "`analysis` text COMMENT '题解析',"
							+ "`make_time` int(11) DEFAULT '0' COMMENT '做的时间',"
							+ " `yes_num` int(11) DEFAULT '0' COMMENT ' 做对总人数',"
							+ "  `error_num` int(11) DEFAULT '0' COMMENT ' 做错总人数',"
							+ "`make_num` int(11) DEFAULT '0' COMMENT '  做的总人数',"
							+ "  `weight` int(11) DEFAULT '0' COMMENT '权重  越大越排前面',"
							+ " `create_time` int(11) DEFAULT '0',"
							+ " `chapter_id` int(11),"
							+ " `section_id` int(11),"
							+ " `spot_id` int(11),"
							+ " `subdivisionPointId` int(11),"
							+ " "
							+ ") ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8;");
			
			
			if(vo.getIsEncode()!=null&&vo.getIsEncode()==1){
				return new JsonSuccessResult(session.getId(), ZipUtil.compress(data.toString()));
			}
			return new JsonSuccessResult(session.getId(), data);

		} catch (Exception e) {
			e.printStackTrace();
			return new JsonFailResult(session.getId(), 1, "后台报错",
					e.getMessage());
		}
	}
/**
 * 检查数据库
 * @param model
 * @param vo
 * @param br
 * @param session
 * @return
 */
	@RequestMapping("/inspectDataBase")
	@ResponseBody
	public JsonResult inspectDataBase(Model model,
			@Valid QuestionsCondition vo, BindingResult br, HttpSession session) {
		if (br.hasErrors())
			return new JsonFailResult(session.getId(), br.getAllErrors().get(0)
					.getDefaultMessage());
		try {

			QuestionsVo questions = new QuestionsVo();
			questionsService.insert(questions);
			return new JsonSuccessResult(session.getId(), "成功");
		} catch (Exception e) {
			e.printStackTrace();
			return new JsonFailResult(session.getId(), 1, "后台报错",
					e.getMessage());
		}
	}
	/**
	 * 考题后的提交
	 * @param model
	 * @param vo
	 * @param br
	 * @param session
	 * @return
	 */
	@RequestMapping("/subtimQuestions")
	@ResponseBody
	@OAuthRequired
	public JsonResult subtimquestions(Model model, @Valid QuestionsSubtimCondition vo,
			BindingResult br, HttpSession session) {
		UsersVo user = (UsersVo) session.getAttribute(Consts.LOGIN_USER);
		if(user==null){
			user=new UsersVo();
			user.setUserId(0);
		}
		if (br.hasErrors())
			return new JsonFailResult(session.getId(), br.getAllErrors().get(0)
					.getDefaultMessage());
		//	学习报告
		if(vo.getIsCollection()==1){
			  LearnReportVo learnReport=new LearnReportVo();
			   learnReport.setQuestionsTypeId(vo.getQuestionsTypeId());
			   learnReport.setUserId(vo.getUserId());
			   learnReport.setType(vo.getType());
			   learnReport.setTitle(vo.getTitle());
			   learnReport.setYesFraction(vo.getYesFraction());
			   learnReport.setTotalFraction(vo.getTotalFraction());
			   learnReport.setAverageFraction(vo.getAverageFraction());
			   learnReport.setAverageTime(vo.getAverageTime());
			   learnReport.setCountryTime(vo.getCountryTime());
			  long l=  new Date().getTime();
			   learnReport.setCreateTime((int)(l/1000));
			   learnReport.setAnswerRate(vo.getAnswerRate());
			   learnReportService.insert(learnReport);
				return new JsonSuccessResult(session.getId(), "成功","");
		}
		
		//事务开启
		TransactionStatus transactionStatus=	questionsService.getTransactionStatus();
		int error=0;
		//题的统计
		try {
			String[] quString=vo.getQuestionsId().split(",");
			String[] makeTime=	vo.getQuestionsMakeTime().split(",");
			QuestionsVo questionsVo=null;
			//时间
			for (int i = 0; i < quString.length; i++) {
				int temp=	Integer.valueOf(quString[i]);
				error=temp;
				questionsVo=	questionsService.findById(temp);
				if(questionsVo!=null&&temp>0){
					questionsVo.setMakeTime(questionsVo.getMakeTime()+Integer.valueOf(makeTime[i]));
					questionsVo.setMakeNum(questionsVo.getMakeNum()+1);
					questionsService.updateSelective(questionsVo);
				}
			
			}
			String[] quesYesNum= 	vo.getQuestionsYesNum().split(",");
			String[] errorNum=vo.getQuestionsErrorNum().split(",");
		//作对
			for (int i = 0; i < quesYesNum.length; i++) {
				int temp=	Integer.valueOf(quesYesNum[i]);
				error=temp;
				questionsVo=	questionsService.findById(temp);
				if(questionsVo!=null&&temp>0){
					questionsVo.setYesNum(questionsVo.getYesNum()+1);
					questionsService.updateSelective(questionsVo);
				}
				
			}
			//做错
			for (int i = 0; i < errorNum.length; i++) {
			int temp=	Integer.valueOf(errorNum[i]);
			error=temp;
				questionsVo=	questionsService.findById(temp);
				if(questionsVo!=null&&temp>0){
					questionsVo.setErrorNum(questionsVo.getErrorNum()+1);
					questionsService.updateSelective(questionsVo);
				}
		
			}
			System.out.println("事务提交");
			questionsService.commit(transactionStatus);
		} catch (Exception e) {
			// TODO: handle exception
			questionsService.rollback(transactionStatus);
			return new JsonFailResult(session.getId(), 1, "后台报错,"+	error+"id找不到",
					e.getMessage());
		}
		
		try {

			QuestionsTypeVo questionsTypeVo=  questionsTypeService.findById(vo.getQuestionsTypeId());
			//做的总数+1
			questionsTypeVo.setStudyNum(questionsTypeVo.getStudyNum()+1);
			//做对的总分数
			questionsTypeVo.setMakeFraction(questionsTypeVo.getMakeFraction()+vo.getYesFraction());
			//做的时间
			questionsTypeVo.setMakeTime(questionsTypeVo.getMakeTime()+vo.getMakeTime());
			questionsTypeVo.setMakeNum(questionsTypeVo.getMakeNum()+1);
			questionsTypeService.updateSelective(questionsTypeVo);
			
			return new JsonSuccessResult(session.getId(), "成功","");
		} catch (Exception e) {
			e.printStackTrace();
			return new JsonFailResult(session.getId(), 1, "后台报错",
					e.getMessage());
		}
	}
	/**
	 * 初始化题
	 * @param model
	 * @param vo
	 * @param br
	 * @param session
	 * @return
	 */
	@RequestMapping("/questionsInitialization")
	@ResponseBody
	//@OAuthRequired
	public JsonResult questionsInitialization(Model model, @Valid QuestionsQueryCondition vo,
			BindingResult br, HttpSession session) {
		UsersVo user = (UsersVo) session.getAttribute(Consts.LOGIN_USER);
		if(user==null){
			user=new UsersVo();
			user.setUserId(0);
		}
		if (br.hasErrors())
			return new JsonFailResult(session.getId(), br.getAllErrors().get(0)
					.getDefaultMessage());
		try {
			JSONObject oJsonObject=new JSONObject();
			if(vo.getQuestionsTypeId()!=null&&vo.getQuestionsTypeId()!=0){
				QuestionsTypeVo questionsTypeVo=	questionsTypeService.findById(vo.getQuestionsTypeId());
				oJsonObject.put("makefraction", questionsTypeVo.getMakeFraction());
				oJsonObject.put("maketime", questionsTypeVo.getMakeTime());
				oJsonObject.put("studynum", questionsTypeVo.getStudyNum());
				oJsonObject.put("questionssum", questionsTypeVo.getQuestionsSum());
				oJsonObject.put("fractionsum", questionsTypeVo.getFractionSum());
				
			}
			List<QuestionsVo> questionsVos=	new ArrayList<QuestionsVo>();
			if(vo.getQuestionsIdS()!=null&&vo.getQuestionsIdS()!=""){
			String[]	array=	vo.getQuestionsIdS().split(",");
				
				for (int i = 0; i < array.length; i++) {
					questionsVos.add(questionsService.findById(Integer.valueOf(array[i])));
				}
			}else{
				questionsVos=	questionsService.findQuestionsPage(vo);
			}
			
			QuestionsVo questionsVo;
			JSONObject object;
			JSONArray array=new JSONArray();
			for (int i = 0; i < questionsVos.size(); i++) {
				questionsVo=questionsVos.get(i);
				object=new JSONObject();
				object.put("Id", questionsVo.getId());
				object.put("error", questionsVo.getErrorNum());
				object.put("make", questionsVo.getMakeNum());
				object.put("type", questionsVo.getType());
				if( questionsVo.getImage()==null|| questionsVo.getImage()==""){
					object.put("image","");
				}else{
					object.put("image","http://" + bucketName + "."
							+ img_endpoint + "/" + questionsVo.getImage());
				}
				
				object.put("url","http://" + bucketName + "."
						+ img_endpoint + "/");
				if(questionsVo.getImage2()==null||questionsVo.getImage2()==""){
					object.put("image2","");
				}else{
					object.put("image2",questionsVo.getImage2());
				
				}
				object.put("maketime", questionsVo.getMakeTime());
				object.put("year", questionsVo.getYear());
				object.put("yes", questionsVo.getYesNum());
				object.put("fraction", questionsVo.getFraction());
				QuestionsCollectionCondition questionsCollectionCondition=new QuestionsCollectionCondition();
				questionsCollectionCondition.setQuestionsId(questionsVo.getId());
				questionsCollectionCondition.setCollectionPeople(user.getUserId());
				List<QuestionsCollectionVo> questionsCollectionVos=   questionsCollectionService.findQuestionsCollectionPage(questionsCollectionCondition);
				if(questionsCollectionVos.isEmpty()){
					object.put("isPraise", "no");
				}else{
					object.put("isPraise", "yes");
				}
				array.add(object);
			}
			oJsonObject.put("list", array);
			return new JsonSuccessResult(session.getId(), "成功",oJsonObject);
		} catch (Exception e) {
			e.printStackTrace();
			return new JsonFailResult(session.getId(), 1, "后台报错",
					e.getMessage());
		}
	}
	@RequestMapping("/questionsAdd")
	@ResponseBody
	public JsonResult questionsAdd(Model model, @Valid QuestionsCondition vo,
			BindingResult br, HttpSession session) {
		if (br.hasErrors())
			return new JsonFailResult(session.getId(), br.getAllErrors().get(0)
					.getDefaultMessage());
		try {

			QuestionsVo questions = new QuestionsVo();
			questionsService.insert(questions);
			return new JsonSuccessResult(session.getId(), "成功");
		} catch (Exception e) {
			e.printStackTrace();
			return new JsonFailResult(session.getId(), 1, "后台报错",
					e.getMessage());
		}
	}

	@RequestMapping("/questionsEdit")
	public JsonResult questionsEdit(Model model, @Valid QuestionsCondition vo,
			BindingResult br, HttpSession session) {
		if (br.hasErrors())
			return new JsonFailResult(session.getId(), br.getAllErrors().get(0)
					.getDefaultMessage());

		try {
			QuestionsVo questions = new QuestionsVo();

			questionsService.updateSelective(questions);

			return new JsonSuccessResult(session.getId(), "成功");

		} catch (Exception e) {
			e.printStackTrace();
			return new JsonFailResult(session.getId(), 1, "后台报错",
					e.getMessage());
		}
	}

}
